import type { RainbowDataType, SettingType } from './interface'

export const transformData = (data: RainbowDataType[]) => {
    const newArr = data.map(item => {
        // 将大于1的投入程度拆分成多个投入程度
        const settings: SettingType[] = []
        item.settings.forEach(i => {
            if (Number(i.grade) > 1) {
                for (let index = 1; index <= Number(i.grade); index++) {
                    settings.push({ ...i, grade: index })
                }
            } else {
                settings.push(i)
            }
        })
        // 按照投入程度从小到大排序；相同投入程度的按照年龄从小到大排序
        settings.sort((a, b) => {
            if (Number(a.grade) === Number(b.grade)) {
                return Number(a.age_end) - Number(b.age_end)
            }
            return Number(a.grade) - Number(b.grade)
        })
        // 将投入程度相同的串联起来
        const newSettings: SettingType[] = []
        let index = 0
        settings.map(i => {
            if (newSettings[index]) {
                if (newSettings[index].grade === i.grade && Number(newSettings[index].age_end) + 1 === Number(i.age_start)) {
                    newSettings[index].age_end = i.age_end
                } else if (Number(newSettings[index].grade) === 1 && Number(newSettings[index].age_end) < Number(i.age_end)) {
                    // 投入程度为1的从头串联到尾
                    newSettings[index].age_end = i.age_end
                } else {
                    newSettings.push(i)
                    index++
                }
            } else {
                newSettings.push(i)
            }
        })
        return {
            ...item,
            settings: newSettings,
        }
    })
    return newArr
}
